from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
import re
import requests
import threading
import prettytable as pt
import time
from random import choice

from tkinter import ttk
# tb=pt.PrettyTable()
# tb.field_names=['序号','歌曲名','歌手','专辑']
hh=0


class Application(Frame):
    def __init__(self,master):
        super().__init__(master)
        self.master=master
        self.pack()
        self.CreateWidget()



    def CreateWidget(self):
        self.label1 = Label( text='请输入要搜索的歌曲或歌手名：', fg='black', font=("楷体"))
        self.label1.place(relx=0.01,rely=0.55)
        self.label2=Label(text="请输入返回第几页:",font=('楷体'))
        self.label2.place(relx=0.01,rely=0.6)
        self.label2.place(relx=0.01, rely=0.6)
        self.label3 = Label(text="请输入每一页返回的数量:", font=('楷体'))
        self.label3.place(relx=0.01,rely=0.65)
        self.label4 = Label(text="请输入要下载歌曲的序号,输入0下载全部：", font=('楷体'))
        self.label4.place(relx=0.01, rely=0.85)
        self.label5 = Label(text="请选择下载歌曲的路径：", font=('楷体'))
        self.label5.place(relx=0.01, rely=0.75)

        text1=StringVar()
        self.entry1=Entry(textvariable=text1,w=20)
        self.entry1.place(relx=0.5,rely=0.55)
        text2=StringVar()
        self.entry2=Entry(textvariable=text2)
        self.entry2.bind('<KeyPress>',
                         lambda e: e if e.keycode==8  or e.keycode==46 or  e.char in set('0123456789') else "break")
        self.entry2.place(relx=0.5,rely=0.6)
        text3=StringVar()
        self.entry3=Entry(textvariable=text3)
        self.entry3.place(relx=0.5,rely=0.65)
        self.entry3.bind('<KeyPress>',
                         lambda e: e if e.keycode == 8 or e.keycode == 46 or e.char in set('0123456789') else "break")
        self.folder_path=StringVar()
        self.entry4 = Entry(textvariable=self.folder_path)
        self.entry4.place(relx=0.5, rely=0.75)
        text4=StringVar()
        self.entry5=Entry(textvariable=text4)
        self.entry5.place(relx=0.62, rely=0.85,width=70)
        self.entry5.bind('<KeyPress>',
                         lambda e: e if e.keycode == 8 or e.keycode == 46 or e.char in set('0123456789') else "break")


        self.btn1 = Button(text='搜索', fg='red', font='楷体', command=self.do)
        self.btn1.place(relx=0.85, rely=0.595)
        self.btn2 = Button(text='下载', fg='red', font='楷体', command=self.pooll)
        self.btn2.place(relx=0.85, rely=0.84)
        self.btn3 = Button(text="Browse", fg='red',command=self.browse_button)
        self.btn3.place(relx=0.85,rely=0.74)


    def downinfo(self):
        if self.entry1.get()=='' or self.entry2.get()==''or self.entry3.get()=='' or self.filename=='' or self.entry5.get()=='':
            messagebox.showinfo("下载失败", '信息不足')
        else:
            messagebox.showinfo("下载信息",'下载成功,请稍等！')


    def showinfo(self):
        if self.entry1.get()=='' or self.entry2.get()==''or self.entry3.get()=='':
            messagebox.showinfo("查找失败", '信息不足')
        else:
            messagebox.showinfo("查找歌曲",'查找成功，请稍等！')


    def do(self):
        self.showinfo()
        self.delButton()
        a, b, c = self.search()
        self.a=a
        self.b=b
        self.c=c
        self.respond(a, b, c)
        # tb.clear()
        # tb.field_names = ['序号', '歌曲名', '歌手', '专辑']

    def browse_button(self):
        # Allow user to select a directory and store it in global var
        # called folder_path
        global folder_path
        self.filename = filedialog.askdirectory()
        self.folder_path.set(self.filename)



    def search(self):
        global c
        a = self.entry1.get()
        print(a)
        if a == '-1':
            exit()
        global b
        c =eval( self.entry2.get())

        b = eval( self.entry3.get())
        return a, b, c

    def delButton(self):
        x = tree.get_children()
        for item in x:
            tree.delete(item)
    def respond(self,a, b, c):
        url = f'http://search.kuwo.cn/r.s?all={a}&ft=music&rformat=json&encoding=utf8&rn={b}&pg={c}&callback=song&vipver=MUSIC_8.0.3.1'
        global headers
        global proxies_list
        global hh
        proxies_list = [{'https': '111.187.9.164:80'},
                        {'https': '114.87.232.221:80'},
                        {'https': '180.160.39.237:80'},
                        {'https': '180.160.39.237:80'}
            ,
                        {'https': '111.187.11.217:80'}]
        proxies = proxies_list[hh]
        hh += 1
        if hh > 4:
            hh = 0
        usera_agent = [
            'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
            'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
            'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0',
            'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5',
            'MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1']
        User_agent = (choice(usera_agent))

        headers = {

            'User-Agent': User_agent}

        response = requests.get(url=url, headers=headers, proxies=proxies).text

        text = eval((response[17:-40]))
        count = 0
        global url_list
        global name_list
        url_list = []
        name_list = []
        for i in range((b)):
            info_list = text['abslist'][i]
            id = (info_list['MUSICRID'])
            name = info_list['SONGNAME']
            artist = info_list['ARTIST']
            album = info_list['ALBUM']
            song_id = id[6:]
            count += 1
            name_list.append(name)
            global download
            i = 1
            # print(song_id,name,artist,album)
            for tries in range(5):
                try:
                    song_url = f'http://www.kuwo.cn/api/v1/www/music/playUrl?mid={song_id}&type=music&type=convert_url&br=320kmp3'
                    download = requests.get(url=song_url, headers=headers, proxies=proxies).text
                    dd = download[150]


                except:
                    print('debug')
                    if tries < 5:
                        time.sleep(0.3)
                        continue
                    else:
                        print('5次尝试均失败')
                        break
                else:
                    break

            # tb.add_row([count, name, artist, album])
            load_url = re.findall('https://(.*?)mp3', download)
            download_url = 'https://' + (load_url)[0] + 'mp3'
            url_list.append(download_url)
            # tb.align['歌曲名'] = 'l'
            # tb.align['歌手'] = 'r'
            # tb.align['专辑'] = 'r'

            tree.insert('',END,values=(count,name,artist,album))
            tree.pack()









    def downloading(self):
        self.downinfo()
        while True:
            ask = eval(self.entry5.get())
            num = ask - 1
            if ask == 0:
                for i in range(b):
                    f = requests.get(url=url_list[i], headers=headers).content
                    with open(f'{self.filename}//' + name_list[i].replace('《', '').replace('》', '').replace('|', '') + '.mp3',
                              mode='wb') as fp:

                        fp.write(f)
                        # print(f'第{i + 1}首下载成功')

                # print('下载完成！')
                # return self.do()

            else:
                f = requests.get(url=url_list[num], headers=headers).content
                with open(f"{self.filename}\\" + name_list[num].replace('《', '').replace('》', '').replace('|', '') + '.mp3',
                          mode='wb') as fp:
                    fp.write(f)
            return ()
                    # print('下载完成！')
                # return self.downloading
    def pooll(self):
        self.t=threading.Thread(target=self.downloading)
        self.t.start()




root=Tk()


root.geometry('500x500+200+200')
root.title("音乐")
tree=ttk.Treeview(root)
tree["columns"] = ("序号", "歌曲名", "歌手", "专辑")
tree['show']='headings'
tree.column("序号", width=100)  # #设置列
tree.column("歌曲名", width=100)
tree.column("歌手", width=100)
tree.column("专辑", width=100)
tree.heading("序号", text="序号")  # #设置显示的表头名
tree.heading("歌曲名", text="歌曲名")
tree.heading("歌手", text="歌手")
tree.heading("专辑", text="专辑")
tree.place(relx=0.1, rely=0)
app=Application(master=root)

root.mainloop()
